package com.jollychic.www.roomdatebasedemo.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jollychic.www.roomdatebasedemo.DaoManager;
import com.jollychic.www.roomdatebasedemo.R;
import com.jollychic.www.roomdatebasedemo.model.StoreEntity;

import io.reactivex.Completable;
import io.reactivex.schedulers.Schedulers;

/**
 * desc: 更改数据 <br/>
 * author: 李超杰 <br/>
 * time: 2018/4/22 17:42 <br/>
 * since: V 6.1X <br/>
 */

public class FragmentUpdate extends Fragment {

    private AppCompatEditText updateId;
    private AppCompatEditText updateName;
    private AppCompatButton updateButton;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = LayoutInflater
                .from(getContext())
                .inflate(R.layout.fragment_update, container, false);

        updateId = view.findViewById(R.id.et_update_id);
        updateName = view.findViewById(R.id.et_update_name);
        updateButton = view.findViewById(R.id.bt_update);

        loadListener();
        return view;
    }

    private void loadListener() {
        updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                update();
            }
        });
    }

    private void update() {
        if (TextUtils.isEmpty(getUpdateId())) {
            return;
        }
        if (TextUtils.isEmpty(getUpdateName())) {
            return;
        }

        Completable
                .fromRunnable(new Runnable() {
                    @Override
                    public void run() {
                        final StoreEntity storeEntity = new StoreEntity();
                        storeEntity.setStoreId(getUpdateId());
                        storeEntity.setStoreName(getUpdateName());
                        DaoManager.getInstance().getIStoreDao().update(storeEntity);
                    }
                })
                .subscribeOn(Schedulers.io())
                .subscribe();
    }


    private String getUpdateId() {
        return updateId.getText().toString().trim();
    }

    private String getUpdateName() {
        return updateName.getText().toString().trim();
    }
}
